#!/bin/bash

set -euo pipefail

cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

source "vendor.bash/github.com/reconquest/import.bash/import.bash"

import:use "github.com/reconquest/hastur.bash"
import:use "github.com/reconquest/containers.bash"
import:use "github.com/reconquest/progress.bash"
import:use "github.com/reconquest/test-runner.bash"
import:use "github.com/reconquest/tests.sh"
import:use "github.com/reconquest/go-test.bash"
import:use "github.com/reconquest/ssh-test.bash"

import:include tests/build.sh
import:include tests/orgalorg.sh
import:include tests/deps.sh

:deps:check

test-runner:set-custom-opts \
    --keep-containers \
    --keep-images \
    --containers-count:

test-runner:handle-custom-opt() {
    case "$1" in
        --keep-containers)
            containers:keep-containers
            hastur:keep-images
            ;;

        --keep-images)
            hastur:keep-images
            ;;

        --containers-count)
            containers:set-count "$2"
            ;;
    esac
}

progress:spinner:new _progress_spinner

test-runner:progress() {
    if [ "${1:-}" = "stop" ]; then
        printf " ok."
    else
        progress:spinner:spin "$_progress_spinner" > /dev/null
    fi
}

:init() {
    go-test:set-output-dir "$(readlink -f .)"
    go-test:build orgalorg

    hastur:init openssh,pam,util-linux,tar,iproute2,sudo,sed,procps-ng,systemd
}

:cleanup() {
    containers:wipe

    hastur:destroy-root

    progress:spinner:stop "$_progress_spinner"

    go-test:merge-coverage
}

:init 2> >(progress:spinner:spin "$_progress_spinner" > /dev/null)

trap :cleanup EXIT

test-runner:run "${@}"
